package com.avengers.core.kit;

import com.avengers.core.bean.enums.*;
import com.avengers.core.exception.SaveFileException;
import com.jfinal.kit.Base64Kit;
import com.jfinal.kit.HashKit;
import com.jfinal.upload.UploadFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import static com.avengers.core.bean.Numbers.INT_0;

/**
 * @author yu.wang
 * @since 2018-04-11 下午8:43
 */
public class FileKit {
    private static final Logger logger = LoggerFactory.getLogger(FileKit.class);
    private static final String SEPARATOR = File.separator;
    private static final int MAX_RETRY_TIMES = 5;
    private static final Duration DEFAULT_TIME_OUT = Duration.ofMinutes(1);

    /**
     * 获取文件类型
     *
     * @param inputStream 文件input流
     * @return 文件类型
     */
    public static FileType getType(InputStream inputStream) {
        if (null == inputStream) {
            return null;
        }
        int off = 0, length = 28;
        try {
            byte[] b = new byte[length];
            if (inputStream.read(b, off, length) > 0) {
                String fileHead = bytesToHexString(b);
                if (fileHead == null || fileHead.isEmpty()) {
                    return null;
                }
                fileHead = fileHead.toUpperCase();
                FileType[] fileTypes = FileType.values();

                for (FileType type : fileTypes) {
                    if (fileHead.startsWith(type.getValue())) {
                        return type;
                    }
                }
            }
        } catch (IOException e) {
            return null;
        }

        return null;
    }

    /**
     * 将文件头转换成16进制字符串
     *
     * @param src 原生byte
     * @return 16进制字符串
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length == 0) {
            return null;
        }
        for (byte b : src) {
            int v = b & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static String getDownloadFilePath(String baseDir, String fileName, String... realDirs) {
        File baseDirFile = new File(baseDir);
        if (!baseDirFile.exists() || !baseDirFile.isDirectory()) {
            throw new RuntimeException("dir [" + baseDir + "] not found!");
        }
        if (null != realDirs && realDirs.length > 0) {
            StringBuilder realDirSB = new StringBuilder();
            for (String dir : realDirs) {
                if (realDirSB.length() > 0) {
                    realDirSB.append(SEPARATOR);
                }
                realDirSB.append(dir);
            }
            if (baseDir.endsWith(SEPARATOR)) {
                baseDir = baseDir + realDirSB;
            } else {
                baseDir = baseDir + SEPARATOR + realDirSB;
            }
        }
        File file = new File(baseDir);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                logger.error("create file dir【{}】error", baseDir);
            }
        }
        return baseDir + SEPARATOR + fileName;
    }

    public static boolean notFileType(UploadFile file, FileType... types) {
        return notFileType(file.getFile(), types);
    }

    public static boolean notFileType(File file, FileType... types) {
        return !isFileType(file, types);
    }

    public static boolean isFileType(UploadFile file, FileType... types) {
        return isFileType(file.getFile(), types);
    }

    public static boolean isFileType(File file, FileType... types) {
        if (null == types || types.length < 1) {
            return false;
        }
        for (FileType type : types) {
            if (isFileType(file, type)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断文件类型
     *
     * @param f    文件
     * @param type 文件类型
     * @return 是否
     */
    public static boolean isFileType(File f, FileType type) {
        try {
            if (null == type) {
                return false;
            }
            InputStream is = Files.newInputStream(f.toPath());
            FileType fileType = getType(is);
            return type.equals(fileType);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    public static boolean checkFileSize(UploadFile file, FileSize minSize, FileSize maxSize) {
        return checkFileSize(file.getFile(), minSize, maxSize);
    }

    public static boolean checkFileSize(File file, FileSize minSize, FileSize maxSize) {
        return !minSize.biggerThan(file.length()) && !maxSize.smallerThan(file.length());
    }

    public static boolean biggerThan(UploadFile file, FileSize fileSize) {
        return biggerThan(file.getFile(), fileSize);
    }

    public static boolean biggerThan(File file, FileSize fileSize) {
        return fileSize.smallerThan(file.length());
    }

    public static boolean smallThan(UploadFile file, FileSize fileSize) {
        return smallThan(file.getFile(), fileSize);
    }

    public static boolean smallThan(File file, FileSize fileSize) {
        return fileSize.biggerThan(file.length());
    }

    public static void delete(UploadFile file) {
        if (null != file) {
            delete(file.getFile());
        }
    }

    public static void delete(File file) {
        if (null != file && file.exists()) {
            if (!file.delete()) {
                logger.error("delete file【{}】fail", file.getAbsolutePath());
            }
        } else if (null != file) {
            logger.error("file【{}】not exit", file.getAbsolutePath());
        }
    }

    public static void delete(String fileDir) {
        if (StringKit.notBlank(fileDir)) {
            File file = new File(fileDir);
            if (file.exists()) {
                delete(file);
            }
        }
    }

    /**
     * 获取文件后缀
     *
     * @param file 文件
     * @return 后缀
     */
    public static String getFileSuffix(UploadFile file) {
        if (null != file) {
            return getFileSuffix(file.getFile());
        }
        return null;
    }

    /**
     * 获取文件后缀
     *
     * @param file 文件
     * @return 后缀
     */
    public static String getFileSuffix(File file) {
        int commaIndex = file.getName().lastIndexOf(".");
        return file.getName().substring(commaIndex).toLowerCase();
    }

    public static String getDownLoadDir() {
        return getTmpPath(FileDirType.download);
    }

    /**
     * 生成随机文件名称
     *
     * @param strings 字符串数组
     * @return MD5
     */
    public static String randomFileName(String... strings) {
        return HashKit.md5(StringKit.concat(System.currentTimeMillis() + "", strings));
    }

    public static File save(String fileEncode, String fileName) {
        Base64.Decoder decoder = Base64.getDecoder();
        String filePathDir = getDownLoadDir();
        File file = new File(filePathDir);
        if (!file.exists()) {
            if (!file.mkdir()) {
                logger.debug("FileKit save file to create dir【{}】fail", filePathDir);
            }
        }
        file = new File(filePathDir + File.separator + fileName + ".jpg");
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            outputStream.write(decoder.decode(fileEncode.getBytes()));
            outputStream.flush();
        } catch (IllegalArgumentException e) {
            throw new SaveFileException("无效的文件编码");
        } catch (Exception e) {
            logger.error("save file to【{}】error:{}", fileName, e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return file;
    }

    public static String toBase64(String filePath) throws IOException {
        return toBase64(new File(filePath));
    }

    public static String toBase64(File file) throws IOException {
        try (FileInputStream fileInputStream = new FileInputStream(file); ByteArrayOutputStream stream = new ByteArrayOutputStream(1000)) {
            byte[] b = new byte[1000];
            int n;
            while ((n = fileInputStream.read(b)) != -1) {
                stream.write(b, 0, n);
            }
            return Base64Kit.encode(stream.toByteArray());
        }
    }

    /**
     * 加压zip文件
     *
     * @param zipFilePath zip文件目录
     * @param targetDir   解压目录
     * @return 解压后文件目录列表
     * @throws IOException error
     */
    public static List<String> unzip(String zipFilePath, String targetDir) throws IOException {
        File zipFile = new File(zipFilePath);
        File dir = new File(targetDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                logger.error("create file dir_{} fail!", targetDir);
            }
        }

        ZipFile zip = new ZipFile(zipFile, Charset.forName(com.avengers.core.bean.enums.Charset.GBK.value));
        List<String> filePathList = new ArrayList<>();
        for (Enumeration<? extends ZipEntry> enumeration = zip.entries(); enumeration.hasMoreElements(); ) {
            ZipEntry entry = enumeration.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = (targetDir + File.separator + zipEntryName).replaceAll("\\*", "/");
            // 判断路径是否存在,不存在则创建文件路径
            String newDir = outPath.substring(0, outPath.lastIndexOf('/'));
            File file = new File(newDir);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    logger.error("create dir_{} fail!", newDir);
                }
            }
            // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if (new File(outPath).isDirectory()) {
                continue;
            }
            filePathList.add(outPath);
            // 输出文件路径信息
            OutputStream out = Files.newOutputStream(Paths.get(outPath));
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }

        return filePathList;
    }

    public static String readText(String filePath) {
        return readText(new File(filePath));
    }

    public static String readText(File file) {
        if (null == file || !file.exists()) {
            return SymbolEnum.empty.string;
        }
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            inputStream = Files.newInputStream(file.toPath());
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append(SymbolEnum.reLine);
            }
            return sb.toString();
        } catch (Exception e) {
            logger.error("read file_{} error: {}", file.getAbsolutePath(), e.getMessage(), e);
        } finally {
            IOKit.close(logger, bufferedReader);
            IOKit.close(logger, inputStreamReader);
            IOKit.close(logger, inputStream);
        }
        return SymbolEnum.empty.string;
    }

    public static String getTmpPath(FileDirType type) {
        String tepDir = System.getProperty("java.io.tmpdir");
        String dir;
        if (tepDir.endsWith(File.separator)) {
            dir = tepDir + type.name();
        } else {
            dir = tepDir + File.separator + type.name();
        }
        File fileDir = new File(dir);
        if (!fileDir.exists()) {
            if (!fileDir.mkdirs()) {
                logger.error("create dir {} fail!", dir);
            }
        }
        return dir;
    }

    public static boolean createFileWithContent(String filePath, String content) {
        File createFile = new File(filePath);
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(createFile);
            outputStream.write(content.getBytes());
            outputStream.flush();
            return true;
        } catch (Exception e) {
            logger.error("create file【{}】with content length_{} error: {}", filePath, StringKit.isBlank(content) ? INT_0 : content.length(), e.getMessage(), e);
        } finally {
            IOKit.close(logger, outputStream);
        }
        return false;
    }

    public static boolean createFile(String filePath, String url) {
        return createFile(filePath, url, 1, (int) DEFAULT_TIME_OUT.toMillis());
    }

    public static boolean createFile(String filePath, String url, int times, int timeout) {
        HttpURLConnection urlConnection = null;
        File createFile = new File(filePath);
        FileOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            urlConnection = createConnection(url, timeout);
            urlConnection.connect();
            inputStream = urlConnection.getInputStream();
            outputStream = new FileOutputStream(createFile);
            int index;
            byte[] bytes = new byte[1024];
            while ((index = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, index);
                outputStream.flush();
            }
            return true;
        } catch (Exception e) {
            logger.error("create file【{}】from url【{}】in {} times error: {}", filePath, url, times, e.getMessage(), e);
            if (times <= MAX_RETRY_TIMES) {
                if (StringKit.notBlank(e.getMessage())) {
                    String timeout1 = "超时", timeout2 = "timed out";
                    if (e.getMessage().contains(timeout1) || e.getMessage().contains(timeout2)) {
                        return createFile(filePath, url, times + 1, timeout * (times + 1));
                    }
                }
            }
        } finally {
            IOKit.close(logger, outputStream);
            IOKit.close(logger, inputStream);
        }
        return false;
    }

    private static HttpURLConnection createConnection(String url, int timeout) throws Exception {
        URL httpsUrl = new URL(url);
        HttpURLConnection urlConnection = (HttpURLConnection) httpsUrl.openConnection();
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod(HttpMethod.GET.name());
        urlConnection.setConnectTimeout(timeout);
        urlConnection.setReadTimeout(timeout);
        urlConnection.setRequestProperty(HttpEnum.CONNECTION.value, HttpEnum.KEEP_ALIVE.value);
        urlConnection.setRequestProperty(HttpEnum.USER_AGENT.value, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");

        return urlConnection;
    }

    public static String copy(String existFilePath, String copyFilePath) {
        return copy(new File(existFilePath), new File(copyFilePath));
    }

    public static String copy(File existFile, File targetFile) {
        if (!existFile.exists() || existFile.isDirectory()) {
            return "source file not exist";
        }
        boolean isFile = targetFile.getName().contains(SymbolEnum.dot.string);
        if (targetFile.exists()) {
            if (isFile) {
                return "target file[" + targetFile.getAbsolutePath() + "] exist";
            }
        }
        if (isFile) {
            File targetPathFile = targetFile.getParentFile();
            if (!targetPathFile.exists()) {
                String failReason = createTargetDir(targetPathFile);
                if (failReason != null) {
                    return failReason;
                }
            }
        } else {
            // 是目录
            String targetPath = targetFile.getAbsolutePath();
            String fileName = existFile.getName();
            String filePath = targetPath + File.separator + fileName;
            targetFile = new File(filePath);
            if (targetFile.exists()) {
                return "target file[" + filePath + "] exist";
            }
            File targetPathFile = new File(targetPath);
            if (!targetPathFile.exists()) {
                String failReason = createTargetDir(targetPathFile);
                if (failReason != null) {
                    return failReason;
                }
            }
        }
        FileOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            inputStream = Files.newInputStream(existFile.toPath());
            outputStream = new FileOutputStream(targetFile);
            int index;
            byte[] bytes = new byte[1024];
            while ((index = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, index);
                outputStream.flush();
            }
            return null;
        } catch (Exception e) {
            logger.error("copy file【{}】 error: {}", existFile, e.getMessage(), e);
        } finally {
            IOKit.close(logger, outputStream);
            IOKit.close(logger, inputStream);
        }
        return "fail";
    }

    private static String createTargetDir(File targetPathFile) {
        boolean createResult = targetPathFile.mkdirs();
        if (!createResult) {
            return "create target dir fail";
        }
        logger.info("create target dir[{}] success", targetPathFile.getAbsolutePath());
        return null;
    }
}
